import React from 'react';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Popconfirm, Card, Spin, Modal, Table, message, Tooltip, Icon} from 'antd';
import routes from './routes';
import {FORM_OPTIONS, TABLE, FORM_ROW_OPTIONS, FIXED_COLUMN_WIDTH} from '../constants';
import SearchSelect from 'Shared/components/SearchSelect';
import DealerSelectPanel from './DealerSelectPanel';
import PartSelectPanel from './PartSelectPanel';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import TextInput from 'Shared/components/TextInput';
import WrappedDatePicker from '../common/WrappedDatePicker';
import WrappedSelect from '../common/WrappedSelect';
import {getDealersSimple} from './api';
import WrappedInputNumber from '../common/WrappedInputNumber';
import Return from '../common/Return';
import styles from './style.css';
import {validateAdd, isSubmitable} from './utils';
import {formatAmount, formatPercent} from '../utils';
const FormItem = Form.Item;
const width = {
    width: '100%'
};
const autosize = {
    minRows: 1
};
const EMPTY_ARRAY = [];
export class Add extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        showDealer: false,
        showPart: false,
        isFetchRate: false,
        isValidateRate: false,
    };

    componentDidMount() {
        this.props.init();
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }

    handleFilterChange = (value, name) => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.onConditionsChange(name, value);
    };
    handleSelectType = (value, name) => {
        const {typeId, details = []} = this.props.conditions;
        if((details.length) && value !== typeId)
            Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'add.selectType.title',
                    defaultMessage: '切换订单类型'
                }),
                content: this.props.intl.formatMessage({
                    id: 'add.selectType.content',
                    defaultMessage: '切换订单类型，将会清空清单信息，是否继续？'
                }),
                onOk: () => {
                    this.props.onConditionsChange(name, value);
                    if(this.props.conditions.dealerId)
                        this.getRaisingRate();
                }
            });
        else {
            this.props.onConditionsChange(name, value);
            if(this.props.conditions.dealerId)
                this.getRaisingRate();
        }
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
    }

    getRaisingRate = () => {
        this.setState({
            isFetchRate: true,
        });
        return this.props.getRaisingRate().then(success => {
            if(success)
                this.setState({
                    isFetchRate: false,
                    isValidateRate: false
                });
            else
                this.setState({
                    isFetchRate: false,
                    isValidateRate: true
                });
        });
    }
    showDealer = () => {
        this.setState({
            showDealer: !this.state.showDealer
        });
    };
    showPart = () => {
        this.setState({
            showPart: !this.state.showPart
        });
    };
    
    onChangePlanQty = (value, id) => {
        this.props.updateDetail({
            id,
            planQuantity: value
        });
    };
    
    onSubmit = () => {
        const result = validateAdd(this.props.conditions, this.props.id);

        if(result) {
            this.setState({
                isValidate: true
            });
            return message.warn(result);
        }

        this.setState({
            loading: true
        });
        this.props.onSubmit().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };
    onSelectDealer = data => {
        this.setState({
            showDealer: false,
            hasOperat: true
        });
        this.props.onSelectDealer(data);
        // 刷新加价率等信息
        if(this.props.conditions.typeId)
            this.getRaisingRate();
    };
    onSelectPart = (record, detailId) => {
        this.setState({
            showPart: false,
            hasOperat: true,
        });
        this.props.onSelectPart(record, detailId);
    };

    onClickDelete = e => {
        const {id} = e.target.dataset;
        this.props.onDeleteDetail(id);
    };
    onClickAddDetail = () => {
        const {typeId} = this.props.conditions;
        if(!typeId)
            return message.warning(this.props.intl.formatMessage({
                id: 'add.addDetail.validate.typeId',
                defaultMessage: '请先选择订单类型'
            }));
        this.setState({showPart: true});
    }
    render() {
        const {dealerId, dealerCode, dealerName, details = []} = this.props.conditions;
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'add.partCode',
                    defaultMessage: '备件编号'
                }),
                dataIndex: 'partCode'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.partName',
                    defaultMessage: '备件名称'
                }),
                dataIndex: 'partName'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.planQuantity',
                    defaultMessage: '订货数量'
                }),
                dataIndex: 'planQuantity',
                className: styles.editCell,
                render: (text, record) => (
                    <FormItem validateStatus={this.state.isValidate && (!record.planQuantity || (record.minPackSize && !Number.isInteger(record.planQuantity / record.minPackSize))) ? 'error' : null}>
                        <WrappedInputNumber
                            min={1}
                            precision={0}
                            defaultValue={1}
                            style={width}
                            id={record.partId}
                            value={record.planQuantity}
                            onBlur={this.onChangePlanQty} />
                    </FormItem>
                )
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.unit',
                    defaultMessage: '计量单位'
                }),
                dataIndex: 'unit'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.taxPrice',
                    defaultMessage: '含税价格'
                }),
                dataIndex: 'taxPrice',
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.totalTaxPrice',
                    defaultMessage: '订货金额'
                }),
                dataIndex: 'totalTaxPrice',
                className: styles.textAlign,
                render: (text, record) => {
                    const {taxPrice = 0, planQuantity = 0} = record;
                    return formatAmount(taxPrice * planQuantity);
                }
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.minPackSize',
                    defaultMessage: '最小包装数'
                }),
                dataIndex: 'minPackSize'
            },
            {
                title: details.length ? (
                    <WrappedPopconfirm
                        id="delete"
                        title={this.props.intl.formatMessage({
                            id: 'add.popconfirm.message',
                            defaultMessage: '是否继续?'
                        })}
                        okText={this.props.intl.formatMessage({
                            id: 'add.popconfirm.confirm',
                            defaultMessage: '确认'
                        })}
                        cancelText={this.props.intl.formatMessage({
                            id: 'add.popconfirm.cancel',
                            defaultMessage: '取消'
                        })}
                        onConfirm={this.props.onDeleteAll}>
                        <a>
                            {this.props.intl.formatMessage({
                                id: 'add.deleteAll',
                                defaultMessage: '清空'
                            })}
                        </a>
                    </WrappedPopconfirm>
                ) : (
                    <a>
                        {this.props.intl.formatMessage({
                            id: 'add.deleteAll',
                            defaultMessage: '清空'
                        })}
                    </a>
                ),
                dataIndex: 'action',
                fixed: 'right',
                width: FIXED_COLUMN_WIDTH,
                render: (text, record) => (
                    <a onClick={this.onClickDelete} data-id={record.partId}>
                        {this.props.intl.formatMessage({
                            id: 'add.delete',
                            defaultMessage: '删除'
                        })}
                    </a>
                )
            }
        ];
        const dealerInfo = dealerId
            ? {
                id: dealerId,
                code: dealerCode,
                name: dealerName
            }
            : null;
        const currentSelectRowKeys = details.map(item => item.partId);
        const raisingRate = this.props.conditions.raisingRate || 0;
        const totalAmount = (details.reduce((a, b) => a + ((b.taxPrice || 0) * (b.planQuantity || 0)), 0)) * (1 + raisingRate);
        return (
            <div className={styles.detail}>
                <Modal
                    title={this.props.intl.formatMessage({
                        id: 'add.dealerModal.title',
                        defaultMessage: '总代信息查询'
                    })}
                    width="80%"
                    maskClosable={false}
                    footer={null}
                    wrapClassName={styles.dataSelectModal}
                    destroyOnClose={true}
                    visible={this.state.showDealer}
                    onCancel={this.showDealer}>
                    <DealerSelectPanel onSelect={this.onSelectDealer} />
                </Modal>
                <Modal
                    title={this.props.intl.formatMessage({
                        id: 'add.partModal.title',
                        defaultMessage: '备件信息查询'
                    })}
                    width="80%"
                    maskClosable={false}
                    footer={null}
                    wrapClassName={styles.dataSelectModal}
                    destroyOnClose={true}
                    visible={this.state.showPart}
                    onCancel={this.showPart}>
                    <PartSelectPanel currentSelectRowKeys={currentSelectRowKeys} brandId={this.props.conditions.brandId} onSelect={this.onSelectPart} getData={this.props.getParts} />
                </Modal>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <Form className="form-standard">
                        <Card
                            title={this.props.intl.formatMessage({
                                id: 'add.card.title',
                                defaultMessage: '订单信息'
                            })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    {this.props.id || this.props.isDealerUser ? (
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'add.form.dealerId',
                                                defaultMessage: '总代'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <span className="value-font">{this.props.conditions.dealerName}</span>
                                        </FormItem>
                                    ) : (
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'add.form.dealerId',
                                                defaultMessage: '总代'
                                            })}
                                            {...FORM_OPTIONS.item}
                                            validateStatus={this.state.isValidate && !this.props.conditions.dealerId ? 'error' : null}
                                            required>
                                            <SearchSelect
                                                value={dealerInfo}
                                                placeholder={this.props.intl.formatMessage({
                                                    id: 'add.form.dealerId.placeholder',
                                                    defaultMessage: '请输入总代名称或编号进行查询'
                                                })}
                                                onSelect={this.onSelectDealer}
                                                onSearch={getDealersSimple}
                                                keyIndex="id"
                                                labelMap={d => `(${d.code})${d.name}`}
                                                onClickSearchBtn={this.showDealer} />
                                        </FormItem>
                                    )}
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.typeId',
                                            defaultMessage: '订单类型'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={this.state.isValidate && !this.props.conditions.typeId ? 'error' : null}
                                        required>
                                        <WrappedSelect
                                            name="typeId"
                                            value={this.props.conditions.typeId}
                                            options={this.props.types}
                                            onChange={this.handleSelectType}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.requiredArrivedDate',
                                            defaultMessage: '要求到货日期'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <WrappedDatePicker
                                            name="requiredArrivedDate"
                                            value={this.props.conditions.requiredArrivedDate}
                                            onChange={this.handleFilterChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.warehouseName',
                                            defaultMessage: '发货仓库'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {this.props.isDealerUser
                                            ? <Spin spinning={this.state.isFetchRate}>
                                                <span className="value-font">{this.props.conditions.warehouseName || '  '}</span>
                                            </Spin>
                                            : <WrappedSelect
                                                disabled={!this.props.conditions.dealerId || !this.props.conditions.typeId || this.state.isFetchRate}
                                                name="warehouseId"
                                                placeholder={this.props.intl.formatMessage({
                                                    id: 'add.form.warehouse.placeholder',
                                                    defaultMessage: '请选择总代和订单类型'
                                                })}
                                                value={this.props.conditions.warehouseId}
                                                options={this.props.warehouses}
                                                onChange={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.raisingRate',
                                            defaultMessage: '加价率'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <Spin spinning={this.state.isFetchRate}>
                                            <span className={'value-font'}>{formatPercent(raisingRate)}</span>
                                            {this.state.isValidateRate ? <Tooltip
                                                title={this.props.intl.formatMessage({
                                                    id: 'add.rateIcon.tooltip',
                                                    defaultMessage: '加价率异常，可能导致总金额不准确，点击图标可重新获取加价率'
                                                })}>
                                                <Icon
                                                    className={styles.rateIcon}
                                                    type="info-circle"
                                                    theme="twoTone"
                                                    twoToneColor="#ff0000"
                                                    data-id="permissionModal"
                                                    onClick={this.getRaisingRate} />
                                            </Tooltip>
                                                : null}
                                        </Spin>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.totalAmount',
                                            defaultMessage: '总金额'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{formatAmount(totalAmount)}</span>
                                    </FormItem>
                                </Col>
                                {this.props.conditions.typeId
                                    ? [
                                        <Col key="creditCode" {...FORM_OPTIONS.col}>
                                            <FormItem
                                                label={this.props.intl.formatMessage({
                                                    id: 'add.form.creditCode',
                                                    defaultMessage: '销售凭证编号'
                                                })}
                                                {...FORM_OPTIONS.item}>
                                                <span className="value-font">{this.props.conditions.creditCode}</span>
                                            </FormItem>
                                        </Col>,
                                        <Col key="creditDescribe" {...FORM_OPTIONS.col}>
                                            <FormItem
                                                label={this.props.intl.formatMessage({
                                                    id: 'add.form.creditDescribe',
                                                    defaultMessage: '销售凭证描述'
                                                })}
                                                {...FORM_OPTIONS.item}>
                                                <span className="value-font">{this.props.conditions.creditDescribe}</span>
                                            </FormItem>
                                        </Col>,
                                        <Col key="orderReasonCode" {...FORM_OPTIONS.col}>
                                            <FormItem
                                                label={this.props.intl.formatMessage({
                                                    id: 'add.form.orderReasonCode',
                                                    defaultMessage: '订购原因编号'
                                                })}
                                                {...FORM_OPTIONS.item}>
                                                <span className="value-font">{this.props.conditions.orderReasonCode}</span>
                                            </FormItem>
                                        </Col>,
                                        <Col key="orderReason" {...FORM_OPTIONS.col}>
                                            <FormItem
                                                label={this.props.intl.formatMessage({
                                                    id: 'add.form.orderReason',
                                                    defaultMessage: '订购原因描述'
                                                })}
                                                {...FORM_OPTIONS.item}>
                                                <span className="value-font">{this.props.conditions.orderReason}</span>
                                            </FormItem>
                                        </Col>
                                    ]
                                    : null}
                            </Row>
                            <Row>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'add.form.remark',
                                        defaultMessage: '备注'
                                    })}
                                    {...FORM_ROW_OPTIONS.item}>
                                    <TextInput type="textarea" autosize={autosize} name="remark" value={this.props.conditions.remark} onBlur={this.handleFilterChange} />
                                </FormItem>
                            </Row>
                        </Card>
                        <Card
                            title={this.props.intl.formatMessage({
                                id: 'add.details',
                                defaultMessage: '清单'
                            })}
                            extra={<Button onClick={this.onClickAddDetail} size="small">
                                {this.props.intl.formatMessage({
                                    id: 'add.btn.add',
                                    defaultMessage: '新增'
                                })}
                            </Button>}>
                            <Table
                                className="white-space-nowrap"
                                rowKey="partId"
                                columns={columns}
                                pagination={false}
                                dataSource={details}
                                {...TABLE}/>
                        </Card>
                        {this.props.submitable && (
                            <Card type="inner" className={styles.noMarginTop}>
                                <Row>
                                    <Col className="col-align-right">
                                        <Button
                                            key="audit"
                                            loading={this.state.loading}
                                            onClick={this.onSubmit}
                                            className={styles.btnMargin}
                                            type="primary">
                                            {this.props.intl.formatMessage({
                                                id: 'add.btn.save',
                                                defaultMessage: '保存'
                                            })}
                                        </Button>
                                    </Col>
                                </Row>
                            </Card>
                        )}
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
            </div>
        );
    }
}
Add.propTypes = {
    conditions: PropTypes.object.isRequired,
    getParts: PropTypes.func.isRequired,
    getRaisingRate: PropTypes.func.isRequired,
    init: PropTypes.func.isRequired,
    isDealerUser: PropTypes.bool.isRequired,
    loading: PropTypes.bool.isRequired,
    submitable: PropTypes.bool.isRequired,
    types: PropTypes.array.isRequired,
    updateDetail: PropTypes.func.isRequired,
    warehouses: PropTypes.array.isRequired,
    onCancel: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onDeleteAll: PropTypes.func.isRequired,
    onDeleteDetail: PropTypes.func.isRequired,
    onSelectDealer: PropTypes.func.isRequired,
    onSelectPart: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    id: PropTypes.string,
    intl: PropTypes.object
};
import {connect} from 'react-redux';
import {
    getDetail,
    saveSubmitCondition,
    clearData,
    querySearch,
    onSubmit,
    selectDealer,
    selectPart,
    deleteAllDetail,
    deleteDetail,
    updateDetail,
    getRaisingRate,
    getParts,
    addInit,
} from './actions';
import {createSelector} from 'reselect';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getEnterprise = selectorFactory(['page', 'domainData', 'initData', 'enterprise']);
const getSubmitData = selectorFactory(['page', 'appState', 'submitData']);
const getConditions = createSelector(
    state => getSubmitData(state),
    state => state.getIn(['page', 'domainData', 'initData', 'isDealerUser']),
    state => getEnterprise(state),
    (submitData, isDealerUser, enterprise) => {
        if(!isDealerUser)
            return submitData;
        const {id, code, name} = enterprise;
        return {
            dealerId: id,
            dealerName: name,
            dealerCode: code,
            ...submitData
        };
    }
);

const getDetailData = createSelector(
    state => getConditions(state),
    state => state.getIn(['page', 'domainData', 'initData', 'brands']),
    (state, ownProps) => ownProps.id,
    (condition, brands, id) => {
        if(id || condition.brandId)
            return condition;
        const data = brands.toJS() || [];
        const brandId = data.length === 1 ? data[0].id : '';
        return {
            brandId,
            ...condition
        };
    }
);
const getTypes = selectorFactory(['page', 'domainData', 'initData', 'types']);
const getInitData = createSelector(
    state => getTypes(state),
    typesData => Array.isArray(typesData) ? typesData.map(item => ({
        text: item.typeName,
        value: item.id
    })) : EMPTY_ARRAY
);
const getWareHouse = createSelector(
    state => state.getIn(['page', 'domainData', 'initData', 'warehouses']),
    data => {
        const warehouses = data.toJS() || EMPTY_ARRAY;
        return warehouses.map((item => ({
            text: item.name,
            value: item.id
        })));
    }
);
const getPermissions = createSelector(
    state => state.getIn(['page', 'domainData', 'permission', 'data']),
    state => state.getIn(['page', 'domainData', 'detail', 'data']),
    (state, ownProps) => ownProps,
    (permissions, detail, ownProps) => {
        const {url, id} = ownProps;
        const {options = EMPTY_ARRAY} = detail.toJS();
        const data = permissions.toJS();
        return isSubmitable(data, options, url, id);
    }
);

const mapStateToProps = (state, ownProps) => ({
    id: ownProps.id,
    submitable: getPermissions(state, ownProps),
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']) || state.getIn(['page', 'domainData', 'initData', 'isFetching']),
    conditions: getDetailData(state, ownProps),
    types: getInitData(state),
    warehouses: getWareHouse(state),
    isDealerUser: state.getIn(['page', 'domainData', 'initData', 'isDealerUser'])
});

const mapDispatchToProps = (dispatch, ownProps) => {
    const props = {
        init: () => {
            if(ownProps.id) return dispatch(getDetail(ownProps.id));
            return dispatch(addInit());
        },
        onConditionsChange: (name, value) => dispatch(saveSubmitCondition(name, value)),
        onSubmit: () =>
            dispatch(onSubmit(ownProps.id)).then(res => {
                if(res.ok) {
                    dispatch(querySearch());
                    ownProps.history.push(routes.query.url());
                }
                return res.ok;
            }),
        onCancel: () => {
            ownProps.history.push(routes.query.url());
        },
        onSelectDealer: data => dispatch(selectDealer(data)),
        onSelectPart: (data, id) => dispatch(selectPart(data, id)),
        onDeleteAll: () => dispatch(deleteAllDetail()),
        onDeleteDetail: id => dispatch(deleteDetail(id)),
        updateDetail: obj => dispatch(updateDetail(obj)),
        getRaisingRate: () => dispatch(getRaisingRate()),
        getParts: conditions => dispatch(getParts(conditions)),
        onUmount: () => dispatch(clearData()),
    };
    return props;
};

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(Add));
